package com.hlkj.baojin.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hlkj.baojin.dao.IDictDAO;
import com.hlkj.baojin.dao.ISoketDataDao;
import com.hlkj.baojin.entity.SoketData;
import com.hlkj.baojin.entity.SoketDataA;
import com.hlkj.baojin.entity.dto.*;
import com.hlkj.baojin.service.DeviceService;
import com.hlkj.baojin.service.IRealDataService;
import com.hlkj.baojin.soket.MyWebSocket;
import com.hlkj.baojin.utils.ValidationUtil;
import com.hlkj.baojin.utils.bean.CopyUtil;
import com.hlkj.baojin.utils.bean.JsonResult;
import com.hlkj.baojin.utils.hik.StringUtils;
import io.swagger.annotations.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author lzx
 * @package com.hlkj.baojin.controller
 * @date 2018/12/17 15:40
 * @Copyright © 2018 HAILIANG Info. Tech Ltd. All rights reserved.
 */
@Api(value = "/bjjk", description = "管理")
@RestController
public class RealDataController {

    @Autowired
    private IRealDataService realDataService;
    @Autowired
    private ISoketDataDao soketDataDao;
    @Value("${real.errTime}")
    private Long errTime;
    @Autowired
    private IDictDAO dictDAO;
    @ApiOperation(value = "信息列表", tags = {"实时信息"})
    @ApiResponses(value = @ApiResponse(code = 200, message = "成功", response = RealDataVO.class))
    @PostMapping(value = "/real/list")
    public ResponseEntity<JsonResult> realList(@RequestBody RealSearchDTO realSearchDTO) {
        return ResponseEntity.ok(realDataService.findList(realSearchDTO));
    }
    /**
     * 实时数据
     */
    @PostMapping(value = "/soketdata")
    public ResponseEntity<String> register(@RequestBody String o) {
        //JSON字符串转对象
        List<SoketData> soketData = JSONObject.parseArray(o,SoketData.class);
        realDataService.updateSocketData(soketData);
        soketDataDao.save(new SoketDataA(o));
        if (!Strings.isEmpty(url)) {
            threadPool.submit(() -> doPost(o));
        }
        return ResponseEntity.ok(null);
    }
    @ApiOperation(value = "波形图列表", tags = {"实时信息"})
    @ApiResponses(value = @ApiResponse(code = 200, message = "成功", response = void.class))
    @PostMapping(value = "/wave/msg")
    public ResponseEntity<JsonResult> waveMsg(@RequestBody WaveSearchDTO waveSearchDTO) {
        return ResponseEntity.ok().body(realDataService.waveMsg(waveSearchDTO));
    }
    /**
     * 定时检测实时数据有没有设备异常
     */
    @Scheduled(cron="${real.cronTime}")
    public void updateSms() {
        realDataService.updateReal(errTime);
    }
    /**
     * @Content 字典接口
     */
    @ApiOperation(value = "索引编号接口", tags = {"实时信息"})
    @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = String.class), @ApiResponse(code = 500, message = "获取失败")})
    @GetMapping("/dict/{type}")
    public ResponseEntity<JsonResult> ziDianKeys(@PathVariable @ApiParam("1.公司编号 2.设备编号") Integer type) {
        return ResponseEntity.ok().body(JsonResult.success(realDataService.getDict(type)));
    }

    /*-------转发------*/
    ExecutorService threadPool = Executors.newFixedThreadPool(3);
    // 要调用的接口方法
//        String url = "http://192.168.1.203:9118/bjjk/soketdata";
    String url = "http://192.168.1.203:9118/dataApi/soketdata";

    public void doPost(String str) {
        HttpPost post = new HttpPost(url);
        try(CloseableHttpClient client = HttpClients.createDefault()) {
            StringEntity s = new StringEntity(str);
//            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "application/json");
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
            post.setConfig(requestConfig);
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            System.out.println(response1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping(value = "/test/updateUrl")
    public void updateUrl(String url) {
        this.url = url;
    }

}
